"""
    进阶版的装饰器[可传参]
"""
from django.core.cache import caches


def cache_check(**cache_kwargs):
    def _cache_check(func):
        def wrapper(self, request, *args, **kwargs):
            """
            构建可传参的装饰器:自定义缓存key
            :param:cache_kwargs: 将装饰器的参数打包成字典
            :param:func: 被装饰的方法[get()方法]
            :param:self request *args **kwargs:方法参数[get()方法参数]
            """
            """
            cache_kwargs:{'key_prefix': 'gd', 'key_param': 'sku_id', 'cache': 'goods_detail', 'expire': 60}
            kwargs:{'sku_id': 1}
            """
            # print('cache_kwargs--->', cache_kwargs)
            # print('kwargs--->', kwargs)

            if "cache" in cache_kwargs:
                CACHES = caches[cache_kwargs["cache"]]
            else:
                CACHES = caches["default"]

            # key: gd1
            key = cache_kwargs["key_prefix"] + str(kwargs["sku_id"])

            # 先看redis中是否有缓存
            response = CACHES.get(key)
            if response:
                print("---数据来自于Redis---")
                return response

            # redis中没有,到MySQL中获取并缓存到redis
            value = func(self, request, *args, **kwargs)
            exp = cache_kwargs.get("expire", 300)
            CACHES.set(key, value, exp)

            return value
        return wrapper
    return _cache_check




















